package com.niiwoo.civet.trade.service.local.databackflow.listener;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.rdb.sharding.api.HintManager;
import com.dangdang.ddframe.rdb.sharding.hint.HintManagerHolder;
import com.niiwoo.civet.trade.dao.entity.DataBackflowStatus;
import com.niiwoo.civet.trade.dao.entity.Project;
import com.niiwoo.civet.trade.dao.entity.ProjectLoanDeviceInfo;
import com.niiwoo.civet.trade.dao.mapper.DataBackflowStatusMapperExt;
import com.niiwoo.civet.trade.enums.DataBackflowStatusDataStatusEnum;
import com.niiwoo.civet.trade.enums.DataBackflowStatusDataTypeEnum;
import com.niiwoo.civet.trade.enums.ProjectFromSourceEnum;
import com.niiwoo.civet.trade.enums.RepaymentTypeEnum;
import com.niiwoo.civet.trade.service.local.common.ProjectCommonService;
import com.niiwoo.civet.trade.service.local.databackflow.DataBackflowService;
import com.niiwoo.civet.user.service.dataflow.UserDataBackFlowDubboService;
import com.niiwoo.tripod.base.component.PrivacyMasks;
import com.niiwoo.tripod.tiancheng.component.TianchengDataFlowService;
import com.niiwoo.tripod.tiancheng.request.df.LoanInfoRequest;
import com.niiwoo.tripod.tiancheng.response.common.TianchengUapResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;

/**
 * @author wping
 * @Description: 借款信息回流监听器
 * @date 2018/4/18 17:19
 */
@Slf4j
@Component
public class LoanInfoListener implements DataBackflowListener {

    @Autowired
    private DataBackflowStatusMapperExt dataBackflowStatusMapperExt;

    @Autowired
    private TianchengDataFlowService tianchengDataFlowService;

    @Autowired
    private DataBackflowService dataBackflowService;

    @Reference(version = "1.0.0")
    private UserDataBackFlowDubboService userDataBackFlowDubboService;

    @Autowired
    private ProjectCommonService projectCommonService;

    @Autowired
    private PrivacyMasks privacyMasks;

    @Override
    public void handle(Long flowExecuteId, String userId, Long projectId, int currentExecuteTimes) {

        final String methodName = "借款信息回流监听到回流请求, flowExecuteId:" + flowExecuteId + ", userId:" + userId + ", projectId:" + projectId;
        if (flowExecuteId == null || StringUtils.isEmpty(userId) || projectId == null) {
            log.error(methodName + "-flowExecuteId/userId/projectId为空");
            return;
        }

        if (!HintManagerHolder.isMasterRouteOnly()) {
            HintManagerHolder.clear();
            HintManager hintManager = HintManager.getInstance();
            hintManager.setMasterRouteOnly();
        }
        // 查询最近一次回流状态情况
        DataBackflowStatus dataBackflowStatus = dataBackflowStatusMapperExt.selectByUserIdProjectIdWithDataType(userId, projectId, DataBackflowStatusDataTypeEnum.LOAN_INFO.getType());
        if (dataBackflowStatus != null) {
            if (DataBackflowStatusDataStatusEnum.BACKFLOW_SUCCESSED.getStatus().byteValue() == dataBackflowStatus.getDataStatus().byteValue()) {
                log.info(methodName + "-数据已经回流，无需重复回流");
                return;
            }
            if (DataBackflowStatusDataStatusEnum.FAILED.getStatus().byteValue() == dataBackflowStatus.getDataStatus().byteValue()) {
                log.info(methodName + "-数据已经回流失败, 非待回流状态");
                return;
            }

            if (DataBackflowStatusDataStatusEnum.WAITING_BACKFLOW.getStatus().byteValue() == dataBackflowStatus.getDataStatus().byteValue()
                    || DataBackflowStatusDataStatusEnum.FAILED_WITH_RETRY.getStatus().byteValue() == dataBackflowStatus.getDataStatus().byteValue()) {
                try {

                    if (!HintManagerHolder.isMasterRouteOnly()) {
                        HintManagerHolder.clear();
                        HintManager hintManager = HintManager.getInstance();
                        hintManager.setMasterRouteOnly();
                    }
                    Project project = projectCommonService.selectByUserIdAndProjectId(userId, projectId);
                    if (project == null) {
                        log.error(methodName + "-标的ID不存在");
                        dataBackflowService.updateAndNotifyBackflowStatusChange(flowExecuteId, false, dataBackflowStatus, currentExecuteTimes, "标的ID不存在");
                        return;
                    }

                    ProjectLoanDeviceInfo projectLoanDeviceInfo = projectCommonService.queryLoanDeviceInfo(projectId);
                    LoanInfoRequest tianchengRequest = new LoanInfoRequest();

                    long createTime = project.getCreateTime().getTime() * 1000;
                    tianchengRequest.setUserId(userId);//借款用户id-必输
                    tianchengRequest.setMobilePhone(this.decryptString(project.getBorrowMobile()));
                    tianchengRequest.setBid(String.valueOf(project.getProjectId()));//标id-必输
                    tianchengRequest.setTitle(project.getTitle());//借款标题
                    tianchengRequest.setBorrowedAmount(project.getHandAmount().floatValue());//借款金额
                    tianchengRequest.setLendRates(project.getBorrowRate().floatValue());//借款利率
                    tianchengRequest.setCreateDate(createTime);//借款时间
                    tianchengRequest.setRepaymentType(RepaymentTypeEnum.enumOf(project.getRepaymentType()).getTianChengRepaymentTypeEnum().getValue());//还款方式--0到期还本息,1每月付息到期还本,2每月等额本息
                    tianchengRequest.setBorrowingMonth(project.getDeadline());//借款时长(按月)
                    tianchengRequest.setTotalPeriods(project.getDeadline());//借款总期数
                    //tianchengRequest.setAmountUsedDesc(project.get);//借款描述
                    tianchengRequest.setType(13);//类型--13:极速借，14：信用借，15体验标
                    tianchengRequest.setCreditType(Integer.valueOf(project.getCreditType()));//授信类型--0:其它,1:社保,2:芝麻,3:学历
                    tianchengRequest.setFromSource(ProjectFromSourceEnum.enumOf(project.getFromSource()).getTianChengFromSourceEnum().getType());//标的来源--0、APP，1、H5活动，2、H5极速借,3、H5淘宝极速借，4、融360
                    tianchengRequest.setLongitude(project.getLongitude());//经度
                    tianchengRequest.setLatitude(project.getLatitude());//纬度
                    tianchengRequest.setApplyTime(createTime);//更新时间

                    if (projectLoanDeviceInfo != null) {
                        //tianchengRequest.setMapType();//地图类型--（0-高德1-百度）
                        //tianchengRequest.setMacAddress();//Mac地址
                        //tianchengRequest.setOperators();//运营商
                        //tianchengRequest.setDownChannel();//下载渠道（渠道号）
                        //tianchengRequest.setAppVersion();//App版本
                        //tianchengRequest.setSimMobilePhone();//当前设备sim卡手机号
                        //tianchengRequest.setOsVersion();//操作系统版本
                        //tianchengRequest.setResolution();//屏幕分辨率
                        //tianchengRequest.setPhoneModel();//设备型号
                        tianchengRequest.setIpAddress(projectLoanDeviceInfo.getIp());//Ip地址
                        tianchengRequest.setWifiSSID(projectLoanDeviceInfo.getWifiSsid());//WIFISSID
                        tianchengRequest.setDeviceId(projectLoanDeviceInfo.getDeviceId());//设备唯一id
                        tianchengRequest.setOs(projectLoanDeviceInfo.getOs());//当前设备操作系统类型
                        tianchengRequest.setBrand(projectLoanDeviceInfo.getBrandType());//设备品牌
                        tianchengRequest.setEquipmentStatus(this.byteConvertToInteger(projectLoanDeviceInfo.getDeviceStatus()));//设备状态(是否越狱orroot)--0-否1-是
                        tianchengRequest.setDualSim(this.byteConvertToInteger(projectLoanDeviceInfo.getDsds()));//是否双卡双待--0-否1-是
                        tianchengRequest.setMapType(this.byteConvertToInteger(projectLoanDeviceInfo.getMapType()));//地图类型（0-高德 1-百度）
                    }

                    log.info(methodName + "-天称借款信息回流开始，请求参数={}", JSON.toJSONString(tianchengRequest));
                    CompletableFuture<TianchengUapResponse> completableFuture = tianchengDataFlowService.loanInfo(tianchengRequest);
                    completableFuture.whenComplete((s, t) -> {
                        // 成功
                        if (s != null) {
                            TianchengUapResponse tianchengUapResponse = (TianchengUapResponse) s;
                            //回流成功
                            if (tianchengUapResponse.isSuccess()) {
                                log.info(methodName + "-天称借款信息回流成功，返回报文:{}", JSON.toJSONString(tianchengUapResponse));
                                dataBackflowService.updateAndNotifyBackflowStatusChange(flowExecuteId, true, dataBackflowStatus, currentExecuteTimes, tianchengUapResponse.getStatus() + "_" + tianchengUapResponse.getMessage());
                            } else {
                                //回流失败
                                log.info(methodName + "-天称借款信息回流失败，返回报文:{}", JSON.toJSONString(tianchengUapResponse));
                                dataBackflowService.updateAndNotifyBackflowStatusChange(flowExecuteId, false, dataBackflowStatus, currentExecuteTimes, tianchengUapResponse.getStatus() + "_" + tianchengUapResponse.getMessage());
                            }
                        }
                        // 异常
                        if (t != null) {
                            log.error(methodName + "-天称借款信息回流异常，异常信息:{}", t);
                            dataBackflowService.updateAndNotifyBackflowStatusChange(flowExecuteId, false, dataBackflowStatus, currentExecuteTimes, t.getMessage());
                        }
                    });
                } catch (Exception e) {
                    log.error(methodName + "-回流异常", e);
                    dataBackflowService.updateAndNotifyBackflowStatusChange(flowExecuteId, false, dataBackflowStatus, currentExecuteTimes, "未知异常");
                }
            }
        } else {
            log.error(methodName + "-未查询到DataBackflowStatus数据，请初始化数据...");
        }
    }

    private Integer byteConvertToInteger(Byte data) {
        return data == null ? null : Integer.valueOf(data);
    }

    /**
     * 解密字符串
     *
     * @param str 密文
     */
    private String decryptString(String str) {
        if (!org.springframework.util.StringUtils.hasText(str)) {
            return null;
        }
        return privacyMasks.decryptPrivacy(str);
    }

    @Override
    public boolean isBackflowSuccess(String userId, Long projectId){
        return dataBackflowService.isBackflowSuccess(userId, projectId, DataBackflowStatusDataTypeEnum.LOAN_INFO);
    }
}
